package edu.polsl.bio.tools.util;

import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.db.SequenceDB;
import org.biojava.bio.seq.io.SeqIOTools;
import org.biojava.bio.symbol.Alphabet;
import org.biojava.bio.symbol.AlphabetManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 14, 2011 1:55:04 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class FastaReader {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(FastaReader.class.getName());

  private Sequence sequence;

  public FastaReader(String filePath) {
    sequence = loadFasta(new File(filePath));
  }

  public String subSeq(int start, int end) {
    return sequence.subStr(start, end);
  }

  public int getFastaLength() {
    return sequence.length();
  }


  public static Sequence loadFasta(File file) {
    BufferedInputStream is = null;
    try {
      is = new BufferedInputStream(new FileInputStream(file));


      //get the appropriate Alphabet
      Alphabet alpha = AlphabetManager.alphabetForName("DNA");

      //get a SequenceDB of all sequences in the file
      SequenceDB db = SeqIOTools.readFasta(is, alpha);
      return db.sequenceIterator().nextSequence();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          log.error("Exception occurred during stream closing ", e);
        }
      }
    }
  }
}
